package com.qianchang.microfinance.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import com.dm.library.utils.DMLog;
import com.dm.library.utils.DateUtil;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.ToastUtil;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.CallRecords;
import com.qianchang.microfinance.bean.Contacts;
import com.qianchang.microfinance.bean.SMSInfoBean;
import com.qianchang.microfinance.view.login.LoginActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by SSC on 2017/12/22.
 *
 *  获取联系人，获取通话记录工具类
 *
 */

public class ContactInforManger {

    private Context context;
    /**
     * 联系人显示名称
     **/
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;
    /**
     * 电话号码
     **/
    private static final int PHONES_NUMBER_INDEX = 1;
    private static final String[] PHONES_PROJECTION = new String[]{
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds
            .Phone.NUMBER, ContactsContract.Contacts.Photo.PHOTO_ID, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};


    public ContactInforManger(Context mContext){
        this.context = mContext;
    }

    /**
     * 加载手机联系人
     */

    public static List<Contacts> getContactsList(Context context) {
        List<Contacts> mSortList = new ArrayList<>();
        ContentResolver resolver = context.getContentResolver();
        Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);

        String phoneNumber;
        String phoneName;
        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {
                phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX).replace(" ", "");
                phoneNumber = phoneNumber.replace("-", "");
                if (null == phoneNumber || "".equals(phoneNumber)) {
                    continue;
                }
                phoneName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
                Contacts sort = new Contacts();
                sort.setMobile(phoneNumber);
                sort.setName(phoneName);
                mSortList.add(sort);
            }
            phoneCursor.close();
        }
        return mSortList;
    }

    /**
     * 通话记录
     *  CallLog.Calls.INCOMING_TYPE      呼入
     *  CallLog.Calls.OUTGOING_TYPE      呼出
     *  CallLog.Calls.MISSED_TYPE       未接
     *
     *  CallLog.Calls.CACHED_FORMATTED_NUMBER      通话记录格式化号码
     *  CallLog.Calls.CACHED_MATCHED_NUMBER     通话记录为格式化号码
     *  CallLog.Calls.CACHED_NAME     联系人名称
     *  CallLog.Calls.TYPE    通话类型
     *  CallLog.Calls.DATE    通话时间(long型)
     *  CallLog.Calls.DURATION     通话时长(秒为单位)
     *  CallLog.Calls.GEOCODED_LOCATION    运营商地址(如：浙江杭州)
     */

    public static List<CallRecords> getCallHistoryList(Context context) {

        List<CallRecords> list = new ArrayList<>();
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = null;
        try {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
                return list;
            }
            cursor = resolver.query(CallLog.Calls.CONTENT_URI, // 查询通话记录的URI
                    new String[]{
                            CallLog.Calls.CACHED_NAME// 通话记录的联系人
                            , CallLog.Calls.NUMBER// 通话记录的电话号码
                            ,
                            CallLog.Calls.DATE// 通话记录的日期
                            , CallLog.Calls.DURATION// 通话时长
                            , CallLog.Calls.TYPE}// 通话类型
                    , null, null, CallLog.Calls.DEFAULT_SORT_ORDER);    // 按照时间逆序排列，最近打的最先显示

            if (null == cursor) {
                return list;
            }
            while (cursor.moveToNext()) {
                String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
                String mobileNub = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
                long dateLong = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
                String callTime = DateUtil.millis2String(dateLong);
                int talkTime = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));
                int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
                String talkType = getCallType(type);

                CallRecords callRecords = new CallRecords();
                callRecords.setName((name == null) ? "未备注联系人" : name);
                callRecords.setMobile(mobileNub);
                callRecords.setCallTime(callTime);
                callRecords.setTalkTime(String.valueOf(talkTime));
                callRecords.setTalkType(talkType);
                list.add(callRecords);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            assert cursor != null;
            cursor.close();
        }
        return list;
    }


    /**
     * 通话类型
     * CallLog.Calls.INCOMING_TYPE      呼入
     * CallLog.Calls.OUTGOING_TYPE      呼出
     * CallLog.Calls.MISSED_TYPE       未接
     * @param anInt
     * @return
     */
    private static String getCallType(int anInt) {
        switch (anInt) {
            case CallLog.Calls.INCOMING_TYPE:
                return "来电";
            case CallLog.Calls.OUTGOING_TYPE:
                return "去电";
            case CallLog.Calls.MISSED_TYPE:
                return "未接";
            default:
                break;
        }
        return "未知";
    }

    /**
     * 获取短信内容
     * @param mContext
     */
    public static List<SMSInfoBean> getSMSInfo(Context mContext) {
        String SMS_URI_ALL = "content://sms/";
        Uri uri = Uri.parse(SMS_URI_ALL);
        Cursor messageCursor = null;
        ContentResolver resolver = null;
        //存储所有短信信息的列表
        List<SMSInfoBean> infos = new ArrayList<SMSInfoBean>();
        try {
            resolver = mContext.getContentResolver();
            String[] projection = new String[]{"_id", "address", "person", "body", "date", "type"};
            uri = Uri.parse(SMS_URI_ALL);

            /*
             * query(Uri uri,String[] project,String selection,
             *             String selectionArgs,String sortOrder)方法各参数含义
             * uri:要读取数据对应的Uri
             * projection:需要读取的字段
             * selection:数据检索的条件
             * selectionArgs:数据检索条件的参数
             * sortOrder:对查询结果排序所依据的字段
             * */
            messageCursor = resolver.query(uri, projection, null, null, "date desc");

            if (messageCursor == null) {
                return infos;
            }
            if (messageCursor.getCount() == 0) {
                messageCursor.close();
                messageCursor = null;
                return infos;
            }

            int phoneNumberColumn = messageCursor.getColumnIndex("address");
            int indexPerson = messageCursor.getColumnIndex("person");
            int smsbodyColumn = messageCursor.getColumnIndex("body");
            int dateColumn = messageCursor.getColumnIndex("date");
            int typeColumn = messageCursor.getColumnIndex("type");
            if (messageCursor != null) {
                while (messageCursor.moveToNext()) {
                    //设置日期显示格式
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    Date date = new Date(Long.parseLong(messageCursor.getString(dateColumn)));

                    SMSInfoBean smsinfo = new SMSInfoBean();

                    String phoneNub = messageCursor.getString(phoneNumberColumn);
                    boolean isPhone = isMobileNO(phoneNub);

                    String cName = "";
                    if (isPhone) {
                        cName = getContactByAddr(mContext,phoneNub);
                        DMLog.i("cName +++++++++++++ " + cName);
                        if(cName == null || cName.equals("")){
                            smsinfo.setName("陌生人");
                        }else{
                            smsinfo.setName(cName);
                        }
                    }else{
                        smsinfo.setName("陌生人");
                    }

                    //此处contactMes为电话号码
                    String mName = messageCursor.getString(indexPerson);
                    smsinfo.setMobile(messageCursor.getString(phoneNumberColumn));
                    smsinfo.setSmsTime(dateFormat.format(date));
                    smsinfo.setSmsContent(messageCursor.getString(smsbodyColumn));
                    infos.add(smsinfo);
                }
            }
            messageCursor.close();

        } catch (Exception e) {
            Log.e("Exception", e.toString());
        } finally {
            if (messageCursor != null) {
                messageCursor.close();
                messageCursor = null;
            }
        }
        return infos;
    }

    /**
     * 根据短信联系号码获取手机联系人姓名
     * @param context
     * @param smsPhone
     * @return
     */

    public static String getContactByAddr(Context context, final String smsPhone) {
        Uri personUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, smsPhone);
        Cursor cur = context.getContentResolver().query(personUri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
        if (cur.moveToFirst()) {
            int nameIdx = cur.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
            String name = cur.getString(nameIdx);
            cur.close();
            return name;
        }
        return null;
    }


    //这个方法判断字符串是不是纯数字
    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }


    //^((\+86)|(86))?(13)\d{9}$
    public static boolean isMobileNO(String mobiles){
        Pattern p = Pattern.compile("^((\\+86)|(86))?[1][3456789][0-9]{9}$");
        Matcher m = p.matcher(mobiles);
       return m.matches();
    }



}
